﻿/********************************************************
 * Module Name    : EnterNewLocationORAddress
 * Project Name   : VAdvantage
 * Purpose        : Account Viewer
 * Created By     : Lakhwinder
 * Created        : 7-sep-2011 
 * Class Used     : AcctViewer
  ******************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Logging;
using VAdvantage.Utility;
using VAdvantage.Model;
using System.Text;
using VAdvantage.Classes;
using System.Data;
using VAdvantage.DataBase;
using VAdvantage.Grids;

namespace VAdvantage.Framework
{
    public partial class AcctViewer : SilverlightDesktop.Controls.Form 
    {
        protected static DataGridColumn[] arrList = null;
        private ToolTip tooltip = new ToolTip();
        #region Interface Variables of AcctViewerConstants
        public const String ACCT_SCHEMA = "C_AcctSchema_ID";
        public const String DOC_TYPE = "DocumentType";
        public const String POSTING_TYPE = "PostingType";
        public const String ORG = "AD_Org_ID";
        public const String ACCT = "Account_ID";
        public const String SELECT_DOCUMENT = "SelectDocument";
        public const String ACCT_DATE = "DateAcct";
        #endregion

        #region Private Variables

       
        private const long SERIALVERSIONUID = 1L;
        //State Info   
        private AcctViewerData _data = null;
        private RModelData tcm = null;
        //Image Icon			
        
        //Logger		
        private static VLogger log = VLogger.GetVLogger(typeof(AcctViewer).FullName);

        /** @todo Display Record Info & Zoom */
        private Label lblSel5 = new Label();
        private Label lblSel6 = new Label();
        private Label lblSel7 = new Label();
        private Label lblSel8 = new Label();
        private SLControls.Controls.VImage btnSel5 = new SLControls.Controls.VImage();
        private SLControls.Controls.VImage btnSel6 = new SLControls.Controls.VImage();
        private SLControls.Controls.VImage btnSel7 = new SLControls.Controls.VImage();
        private SLControls.Controls.VImage btnSel8 = new SLControls.Controls.VImage();
        #endregion

        /// <summary>
        /// Default constructor
        /// </summary>
        public AcctViewer()
            : this(0, 0, 0)
        {
            //InitializeComponent();
        }

        /// <summary>
        /// Detail Constructor
        /// </summary>
        /// <param name="AD_Client_ID">Client AcctViewer</param>
        /// <param name="AD_Table_ID"></param>
        /// <param name="Record_ID"></param>
        public AcctViewer(int AD_Client_ID, int AD_Table_ID, int Record_ID)
          //  : base(true, true, true, true, true, Msg.GetMsg(Envs.GetContext(), "AcctViewer"))
        {
            try
            {
                Envs.SetBusyIndicator(true);
                InitializeComponent();
                vdtpkAccDateFrom.SelectedDate = DateTime.Now;
                LayoutRoot.Background = new SolidColorBrush(GlobalVariable.WINDOW_BACK_COLOR);
               // vdtpkAccDateTo.SelectedDate = DateTime.Now;
                
            }
            catch {
                Envs.SetBusyIndicator(false);
            }
            log.Info("AD_Table_ID=" + AD_Table_ID + ", Record_ID=" + Record_ID);
            //setDefaultCloseOperation(DISPOSE_ON_CLOSE);

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {

                _data = new AcctViewerData(Envs.GetContext(), Envs.CreateWindowNo(this), AD_Client_ID, AD_Table_ID);
                Dispatcher.BeginInvoke(delegate
                {
                    DynInit(AD_Table_ID, Record_ID);
                });
            });
            try
            {
                JbInit();
                //DynInit(AD_Table_ID, Record_ID);
                EventHadler();
                //AEnv.showCenterScreen(this);
                // this.ShowDialog();
               // this.Show();
            }
            catch (Exception e)
            {
                Envs.SetBusyIndicator(false);
                log.Log(Level.SEVERE, "", e);
                Dispose();
            }
        }

        /// <summary>
        /// Static Init.
        /// <pre>
        /// - mainPanel
        /// - tabbedPane
        /// - query
        /// - result
        /// - graphPanel
        /// </pre>
        /// </summary>
        private void JbInit()
        {
           

            //Selection

            groupBox1.Header = Msg.GetMsg(Envs.GetCtx(), "Selection");
            vlblAccSchema.Content = Msg.Translate(Envs.GetCtx(), ACCT_SCHEMA);
            vlblPostType.Content = Msg.Translate(Envs.GetCtx(), POSTING_TYPE);
            vchkSelectDoc.Content = Msg.GetMsg(Envs.GetCtx(), SELECT_DOCUMENT);
            vlblQrg.Content = Msg.Translate(Envs.GetCtx(), ORG);
            vlblAcc. Content = Msg.Translate(Envs.GetCtx(), ACCT);
            vlblAccDate.Content = Msg.Translate(Envs.GetCtx(), ACCT_DATE);

            //Display
            groupBox2.Header = Msg.GetMsg(Envs.GetCtx(), "Display");
            vchkQty.Content = Msg.GetMsg(Envs.GetCtx(), "DisplayQty");
            vchkDisSouce.Content = Msg.GetMsg(Envs.GetCtx(), "DisplaySourceInfo");
            vchkDisDocinfo.Content = Msg.GetMsg(Envs.GetCtx(), "DisplayDocumentInfo");
            vlblSort.Content = Msg.GetMsg(Envs.GetCtx(), "SortBy");
            vlblSumrise.Content = Msg.GetMsg(Envs.GetCtx(), "GroupBy");
            // 
            tabItem1.Header = Utility.Util.CleanMnemonic(Msg.GetMsg(Envs.GetCtx(), "ViewerQuery"));
            tabItem2.Header = Msg.GetMsg(Envs.GetCtx(), "ViewerResult");


           // vdgvRecords.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
            vdgvRecords.HeadersVisibility = DataGridHeadersVisibility.All;

         //   vdgvRecords.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            vdgvRecords.IsReadOnly = true;
            vdgvRecords.AutoGenerateColumns = false;
            // set style properties of datagrid
       //     CommonFunctions.SetDataGridPrperties(vdgvRecords);

            // South
            vlblstatusLine.Foreground =new SolidColorBrush(Colors.Blue);
            vbtnRePost.Content = Msg.GetMsg(Envs.GetCtx(), "RePost");
           
            vbtnRePost.SetValue(ToolTipService.ToolTipProperty, Msg.GetMsg(Envs.GetContext(), "RePostInfo", true));
            //        btnRePost.addActionListener(this);
            vbtnRePost.Visibility = Visibility.Visible;
            vchkforcePost.Content = Msg.GetMsg(Envs.GetCtx(), "Force");
           
            vchkforcePost.SetValue(ToolTipService.ToolTipProperty, Msg.GetMsg(Envs.GetContext(), "ForceInfo", true));
            vchkforcePost.Visibility = Visibility.Visible;
            //        btnRefresh.setIcon(Env.getImageIcon("Refresh16.gif"));
           
            vbtnRefresh.SetValue(ToolTipService.ToolTipProperty, Msg.GetMsg(Envs.GetContext(), "Refresh", true));
            //        btnPrint.setIcon(Env.getImageIcon("Print16.gif"));
            
            vbtnPrint.SetValue(ToolTipService.ToolTipProperty, Msg.GetMsg(Envs.GetContext(), "Print", true));
        }

        /// <summary>
        /// Dynamic Init
        /// </summary>
        /// <param name="AD_Table_ID"></param>
        /// <param name="Record_ID"></param>
        private void DynInit(int AD_Table_ID, int Record_ID)
        {
            FillComboBox(vcmbAccSchema, _data.GetAcctSchema());
            ActionAcctSchema();
            ////
            ListBoxVO lstVo = new ListBoxVO();
            ListBoxVO PostingType = new ListBoxVO();
            ListBoxVO org = new ListBoxVO();
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                lstVo = _data.GetTable();
                PostingType = _data.GetPostingType();
                org = _data.GetOrg();
                Dispatcher.BeginInvoke(delegate
                {
                    FillComboBox(vcmbSelectDoc, lstVo);
                    FillComboBox(vcmbPostType,PostingType);
                    FillComboBox(vcmbOrg, org);
                    ActionTable();
                    bool haveDoc = AD_Table_ID != 0 && Record_ID != 0;
                    vchkSelectDoc.IsChecked = haveDoc;
                    if (haveDoc)
                    {
                        ActionDocument();
                        _data.AD_Table_ID = AD_Table_ID;
                        _data.Record_ID = Record_ID;
                       
                        ActionQuery();
                    }
                    Envs.SetBusyIndicator(false);


                });
            });
            
            //btnSelctDoc.setIcon(m_iFind);
           // vbtnSelctDoc.Content = "";
            ////
           

            ////  Mandatory Elements
           
            //btnAccount.setActionCommand(ACCT);
            vbtnAccount.Name = ACCT;
           // vbtnAccount.Content = "";
            //btnAccount.setIcon(m_iFind);

            ////  Document Select
           
            ActionDocument();
            
            vlblStatuslineT2.Content = " " + Msg.GetMsg(Envs.GetCtx(), "ViewerOptions");
            vlblStatuslineT2.Foreground =new SolidColorBrush(Colors.Blue);


            ////  Initial Query
            
        }

        /// <summary>
        /// Dispose
        /// </summary>
        public void dispose()
        {
            _data.Dispose();
            _data = null;
            base.Dispose();
        }

        /// <summary>
        /// New Acct Schema
        /// </summary>
        private void ActionAcctSchema()
        {
            KeyNamePair kp = (KeyNamePair)vcmbAccSchema.SelectedItem;
            if (kp == null)// && kp == -1)
            {
                return;
            }
            _data.C_AcctSchema_ID = kp.GetKey();
            _data.ASchema = MAcctSchema.Get(Envs.GetCtx(), _data.C_AcctSchema_ID);
            log.Info(_data.ASchema.ToString());
            //
            //  Sort Options
            vcmbSort1.Items.Clear();//removeAllItems();
            vcmbSort2.Items.Clear();//removeAllItems();
            vcmbSort3.Items.Clear();//removeAllItems();
            vcmbSort4.Items.Clear();//removeAllItems();
            SortAddItem(new ValueNamePair("", ""));
            SortAddItem(new ValueNamePair("DateAcct", Msg.Translate(Envs.GetCtx(), "DateAcct")));
            SortAddItem(new ValueNamePair("DateTrx", Msg.Translate(Envs.GetCtx(), "DateTrx")));
            SortAddItem(new ValueNamePair("C_Period_ID", Msg.Translate(Envs.GetCtx(), "C_Period_ID")));
            //
            Label[] labels = new Label[] { vlblProduct,vlblBP, vlblProject, vlblCompaning, lblSel5, lblSel6, lblSel7, lblSel8 };
            SLControls.Controls.VImage[] buttons = new SLControls.Controls.VImage[] { vbtnProduct, vbtnBPartner, vbtnProject, vbtnCampaning, btnSel5, btnSel6, btnSel7, btnSel8 };
            int selectionIndex = 0;

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                MAcctSchemaElement[] elements = _data.ASchema.GetAcctSchemaElements();

                Dispatcher.BeginInvoke(delegate
                {
                    for (int i = 0; i < elements.Length && selectionIndex < labels.Length; i++)
                    {
                        MAcctSchemaElement ase = elements[i];
                        String columnName = ase.GetColumnName();
                        String displayColumnName = ase.GetDisplayColumnName();
                        //  Add Sort Option
                        SortAddItem(new ValueNamePair(columnName, Msg.Translate(Envs.GetCtx(), displayColumnName)));
                        //  Additional Elements
                        if (!ase.IsElementType(X_C_AcctSchema_Element.ELEMENTTYPE_Organization)
                            && !ase.IsElementType(X_C_AcctSchema_Element.ELEMENTTYPE_Account))
                        {
                            labels[selectionIndex].Content = Msg.Translate(Envs.GetCtx(), displayColumnName);
                            labels[selectionIndex].Visibility = Visibility.Visible;
                            try
                            {
                                //buttons[selectionIndex].SetValue(columnName);
                                buttons[selectionIndex].Name = columnName;
                            }
                            catch { }
                            //buttons[selectionIndex].addActionListener(this);
                            //buttons[selectionIndex].setIcon(m_iFind);
                          //  buttons[selectionIndex].Content = "";
                            buttons[selectionIndex].Visibility = Visibility.Visible;
                            selectionIndex++;
                        }
                    }
                    //	don't show remaining
                    while (selectionIndex < labels.Length)
                    {
                        labels[selectionIndex].Visibility = Visibility.Collapsed;
                        buttons[selectionIndex++].Visibility = Visibility.Collapsed;
                    }
                });
            });
        }

        /// <summary>
        /// Add to Sort
        /// </summary>
        /// <param name="vn">name pair</param>
        private void SortAddItem(ValueNamePair vn)
        {
            vcmbSort1.Items.Add(vn);//.addItem(vn);
            vcmbSort2.Items.Add(vn);//.addItem(vn);
            vcmbSort3.Items.Add(vn);//.addItem(vn);
            vcmbSort4.Items.Add(vn);//.addItem(vn);
        }

        /// <summary>
        /// Query
        /// </summary>
        private void ActionQuery()
        {
            //  Parameter Info
            StringBuilder para = new StringBuilder();
            //  Reset Selection Data
            _data.C_AcctSchema_ID = 0;
            _data.AD_Org_ID = 0;

            //  Save Selection Choices
            KeyNamePair kp = (KeyNamePair)vcmbAccSchema.SelectedItem;
            if (kp != null)
            {
                _data.C_AcctSchema_ID = kp.GetKey();
            }
            para.Append("C_AcctSchema_ID=").Append(_data.C_AcctSchema_ID);
            //
            ValueNamePair vp = (ValueNamePair)vcmbPostType.SelectedItem;
            if (vp != null && vp.ToString() != "")
            {
                _data.PostingType = vp.GetValue();
            }
            para.Append(", PostingType=").Append(_data.PostingType);

            //  Document
            _data.documentQuery =(bool) vchkSelectDoc.IsChecked;
            para.Append(", DocumentQuery=").Append(_data.documentQuery);
            if ((bool)vchkSelectDoc.IsChecked)
            {
                if (_data.AD_Table_ID == 0 || _data.Record_ID == 0)
                {
                    return;
                }
                para.Append(", AD_Table_ID=").Append(_data.AD_Table_ID)
                    .Append(", Record_ID=").Append(_data.Record_ID);
            }
            else
            {
               // _data.DateFrom = (DateTime?)vdtpkAccDateTo.GetValue();
                _data.DateFrom = (DateTime?)vdtpkAccDateFrom.SelectedDate;
                para.Append(", DateFrom=").Append(_data.DateFrom);
              //  _data.DateTo = (DateTime?)vdtpkAccDateTo.GetValue();
                _data.DateTo = (DateTime?)vdtpkAccDateTo.SelectedDate;
                para.Append(", DateTo=").Append(_data.DateTo);
                kp = (KeyNamePair)vcmbOrg.SelectedItem;
                if (kp != null)
                {
                    _data.AD_Org_ID = kp.GetKey();
                }
                para.Append(", AD_Org_ID=").Append(_data.AD_Org_ID);
                //
                //Iterator<String> it = _data.whereInfo.values().iterator();
                IEnumerator<String> it = _data.whereInfo.Values.GetEnumerator();
                while (it.MoveNext())
                {
                    para.Append(", ").Append(it.Current);
                }
            }

            //  Save Display Choices
            _data.displayQty = (bool)vchkQty.IsChecked;
            para.Append(", - Display Qty=").Append(_data.displayQty);
            _data.displaySourceAmt = (bool)vchkDisSouce.IsChecked;
            para.Append(", Source=").Append(_data.displaySourceAmt);
            _data.displayDocumentInfo = (bool)vchkDisDocinfo.IsChecked;
            para.Append(", Doc=").Append(_data.displayDocumentInfo);
            //
            if (vcmbSort1.SelectedValue != null)
            {
                _data.sortBy1 = ((ValueNamePair)vcmbSort1.SelectedItem).GetValue();//sortBy1.getSelectedItem()).getValue();
            }
            _data.group1 = (bool)vchkSumriz1.IsChecked;
            para.Append(" - Sorting: ").Append(_data.sortBy1).Append("/").Append(_data.group1);
            if (vcmbSort2.SelectedValue != null)
            {
                _data.sortBy2 = ((ValueNamePair)vcmbSort2.SelectedItem).GetValue();
            }
            _data.group2 = (bool)vchkSumriz2.IsChecked;
            para.Append(", ").Append(_data.sortBy2).Append("/").Append(_data.group2);
            if (vcmbSort2.SelectedValue != null)
            {
                _data.sortBy3 = ((ValueNamePair)vcmbSort3.SelectedItem).GetValue();
            }
            _data.group3 = (bool)vchkSumriz3.IsChecked;
            para.Append(", ").Append(_data.sortBy3).Append("/").Append(_data.group3);
            if (vcmbSort4.SelectedValue != null)
            {
                _data.sortBy4 = ((ValueNamePair)vcmbSort4.SelectedItem).GetValue();
            }
            _data.group4 = (bool)vchkSumriz4.IsChecked;
            para.Append(", ").Append(_data.sortBy4).Append("/").Append(_data.group4);

            vbtnRefreshT2.IsEnabled = false;
            vbtnRefresh.IsEnabled = false;
            //***********************************Set line text
            vlblstatusLine.Content = " " + Msg.GetMsg(Envs.GetCtx(), "Processing");

            log.Config(para.ToString());
            //Causes the currently executing thread object to temporarily pause 
            //and allow other threads to execute. 
            //Thread.yield();
          //  System.Threading.Thread.Sleep(0);

            //  Switch to Result pane
            //tabbedPane.setSelectedIndex(1);
            vTabmain.SelectedIndex = 1;

            //  Set TableModel with Query ***********************FillGrid
            //table.setModel(_data.Query(Env.GetCtx()));
            try
            {
                RModel qry = null;
               // bool chk = true;
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    qry=_data.Query(Envs.GetCtx());
                    Dispatcher.BeginInvoke(delegate
                    {
                        SetModel(qry);
                       // chk =false;
                        Envs.SetBusyIndicator(false);
                    });
                });
                //while (chk)
                //{ }
            }
            catch { }


            vbtnRefreshT2.IsEnabled = true;
            vbtnRefresh.IsEnabled = true;
            //2nd tab status line text
            vlblstatusLine.Content = " " + Msg.GetMsg(Envs.GetCtx(), "ViewerOptions");
        }

        /// <summary>
        /// Set Model
        /// </summary>
        /// <param name="reportModel"></param>
        public void SetModel(RModel reportModel)
        {
            log.Config(reportModel.ToString());
            //vdgvRecords.DataSource = null;
            vdgvRecords.ItemsSource = null;
           // vdgvRecords.DataBindings.Clear();
            
          //  vdgvRecords.SetBinding(null, null);
            vdgvRecords.Columns.Clear();

            //super.setModel(new ResultTableModel(reportModel));
            //
            //TableColumnModel tcm = getColumnModel();

            //  Set Editor/Renderer

            int col = reportModel.GetColumnCount();
            arrList = new DataGridColumn[col];
            
            for (int i = 0; i < col; i++)//tcm.getColumnCount()
            { 
                 
                //TableColumn tc = tcm.getColumn(i); 
                RColumn rc = reportModel.GetRColumn(i);                                   

                List<GridFieldVO> fieldVOs = new List<GridFieldVO>();

                fieldVOs.Add(new GridFieldVO(rc.GetColSQL(), rc.GetColHeader(), FieldType.String));
                DataGridTextColumn txt1 = new DataGridTextColumn();
                txt1.Header = rc.GetColHeader();
                arrList[i] = txt1;

                //vdgvRecords.Rows[0].Cells[i].Value = rc.GetColHeader();
                //if (rc.GetColHeader().Equals(tc.getHeaderValue()))
                //{
                //ResultTableCellRenderer rtcr = new ResultTableCellRenderer(reportModel, rc);
                //tc.setCellRenderer(rtcr);
                //
                //}
                //else
                //{
                //    log.Log(Level.SEVERE, "RColumn=" + rc.GetColHeader() + " <> TableColumn="); //+ tc.getHeaderValue());
                //}
            }

            DataTable dt = new DataTable();
            for (int i = 0; i < arrList.Length; i++)
            {
                
             
                DataColumn dcol = new DataColumn(arrList[i].Header.ToString());

               
                dt.Columns.Add(dcol);
                dt.Columns[i].ColumnName.ToString().Replace("/", " ");
                DataGridTextColumn txtcol = new DataGridTextColumn();
                txtcol.Binding = new System.Windows.Data.Binding(dt.Columns[i].ColumnName);
                txtcol.Header = (dt.Columns[i].ColumnName);
               // txtcol.Width = new DataGridLength(i,new GridLength.Auto);
                //vdgvRecords.Columns.Add(arrList[i]);
                vdgvRecords.Columns.Add(txtcol);
               
               
            }
           // vdgvRecords.MultiSelect = true;
            //vdgvRecords.AutoSize = true;
            //vdgvRecords.Rows.Add(reportModel.GetRowCount());

         //   vdgvRecords.ItemsSource = null;

            
            //for (int i = 0; i < reportModel.GetRowCount(); i++)
            //{
            //    DataRow datarow = new DataRow();
            //    dt.Rows.Add(datarow);
            //}

            for (int row = 0; row < reportModel.GetRowCount(); row++)
            {
                DataRow datarow = new DataRow(dt);
               // dt.Rows.Add(datarow);
                for (int i = 0; i < col; i++)
                {
                   // vdgvRecords.rows[row].Cells[i].Value = reportModel.GetValueAt(row, i);
                    if (reportModel.GetValueAt(row, i) == null)
                    {
                        //datarow.Table.Columns[i].DefaultValue = "";
                        datarow[i] = "";
                    }
                    else
                    {
                       // datarow.Table.Columns[i].DefaultValue = reportModel.GetValueAt(row, i).ToString();
                        datarow[i] = reportModel.GetValueAt(row, i).ToString();
                    }
                   // dt.Rows[row][i] = reportModel.GetValueAt(row, i);
                    
                }
                dt.Rows.Add(datarow);
                    
            }
            //vdgvRecords.DataSource = reportModel.GetRowCount();
            //vdgvRecords.AutoGenerateColumns = true;
            
            vdgvRecords.ItemsSource = dt.GetBindableData(new Connector());
            

        }

        /// <summary>
        /// Document selection
        /// </summary>
        private void ActionDocument()
        {
            bool doc =(bool) vchkSelectDoc.IsChecked;
            vcmbSelectDoc.IsEnabled = doc;
            vbtnSelctDoc.IsEnabled = doc;
            vdtpkAccDateFrom.IsEnabled = !doc;
            vdtpkAccDateTo.IsEnabled = !doc;//setReadWrite
            vcmbOrg.IsEnabled = !doc;
            vbtnAccount.IsEnabled = !doc;
            vbtnProduct.IsEnabled = !doc;
            vbtnBPartner.IsEnabled = !doc;
            vbtnProject.IsEnabled = !doc;
            vbtnCampaning.IsEnabled = !doc;
            btnSel5.IsEnabled = !doc;
            btnSel6.IsEnabled = !doc;
            btnSel7.IsEnabled = !doc;
            btnSel8.IsEnabled = !doc;
        }
        
        /// <summary>
        /// Save Table selection (reset Record selection)
        /// </summary>
        private void ActionTable()
        {
            ValueNamePair vp = (ValueNamePair)vcmbSelectDoc.SelectedItem;
            //_data.AD_Table_ID = ((int)_data.tableInfo.get(vp.getValue())).intValue();
            if (vp != null)
            {
                _data.AD_Table_ID = Utility.Util.GetValueOfInt(_data.tableInfo[vp.GetValue()]);
            }
            log.Config(vp + " = " + _data.AD_Table_ID);
            //  Reset Record
            _data.Record_ID = 0;
     //       vbtnSelctDoc.Content = "";
            //btnSelctDoc.setActionCommand(vp.GetValue() + "_ID");
            vbtnSelctDoc.Name = vp.GetValue() + "_ID";
        }

        
        /// <summary>
        /// Action Button
        /// </summary>
        /// <param name="button">pressed button</param>
        /// <returns>ID</returns>
        private int ActionButton(SLControls.Controls.VImage button)
        {
            String keyColumn = button.Name;//getActionCommand();
            log.Info(keyColumn);
            String whereClause = "IsSummary='N'";
            String lookupColumn = keyColumn;
            if (keyColumn.Equals("Account_ID"))
            {
                lookupColumn = "C_ElementValue_ID";
                MAcctSchemaElement ase = _data.ASchema.GetAcctSchemaElement(X_C_AcctSchema_Element.ELEMENTTYPE_Account);
                if (ase != null)
                {
                    whereClause += " AND C_Element_ID=" + ase.GetC_Element_ID();
                }
            }
            else if (keyColumn.Equals("User1_ID"))
            {
                lookupColumn = "C_ElementValue_ID";
                MAcctSchemaElement ase = _data.ASchema.GetAcctSchemaElement(X_C_AcctSchema_Element.ELEMENTTYPE_UserList1);
                if (ase != null)
                {
                    whereClause += " AND C_Element_ID=" + ase.GetC_Element_ID();
                }
            }
            else if (keyColumn.Equals("User2_ID"))
            {
                lookupColumn = "C_ElementValue_ID";
                MAcctSchemaElement ase = _data.ASchema.GetAcctSchemaElement(X_C_AcctSchema_Element.ELEMENTTYPE_UserList2);
                if (ase != null)
                {
                    whereClause += " AND C_Element_ID=" + ase.GetC_Element_ID();
                }
            }
            else if ((bool)vchkSelectDoc.IsChecked)
            {
                whereClause = "";
            }
            String tableName = lookupColumn.Substring(0, lookupColumn.Length - 3);
            //Info info = Info.Create(this, true, _data.windowNo, tableName, lookupColumn, "", false, whereClause);
            Info info = Info.Create(new ChildWindow(), true, _data.windowNo, tableName, lookupColumn, "", false, whereClause);
            //if (info.LoadedOK())
            //{
            //    //info.Dispose();
            //    info = null;
            //    button.Content = "";
            //    _data.whereInfo.Add(keyColumn, "");
            //    return 0;
            //}
          
          //  info.ShowDialog();
           info.Closed+=(str,ev)=>
            {
                int key = Utility.Util.GetValueOfInt(info.GetSelectedKey());
                String selectSQL = info.GetSelectedSQL();       //  C_Project_ID=100 or ""

                // info = null;
                // if (selectSQL == null || selectSQL.Length == 0 || key == null)
                if (selectSQL == null || selectSQL.Length == 0)
                {
                  //  button.Content = "";
                    //m_data.whereInfo.put(keyColumn, "");    //  no query
                    _data.whereInfo.Remove(keyColumn);//remove select text from button by removeing key     //  no query
                   // button.Width = 44;
                   // return 0;
                }

                //  Save for query
                log.Config(keyColumn + " - " + key);
                if (button == vbtnSelctDoc)                            //  Record_ID
                {
                    _data.Record_ID = Utility.Util.GetValueOfInt(key);
                }
                else
                {
                    try
                    {
                        _data.whereInfo.Add(keyColumn, keyColumn + "=" + key);
                    }
                    catch
                    { }
                }

                //  Display Selection and resize
                string btnContent = "";
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    btnContent = _data.GetButtonText(tableName, lookupColumn, selectSQL);
                    Dispatcher.BeginInvoke(delegate
                    {
                        //button.Content = btnContent;
                        //if (!button.Content.Equals(""))
                        //{
                        //    //button.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
                        //    button.HorizontalContentAlignment = HorizontalAlignment.Left;
                        //    button.VerticalContentAlignment = VerticalAlignment.Center;
                        //    //button.Width = button.Text.Length + 150;
                        //    // button.AutoSize = true;
                        //}
                        //else
                        //{
                        //    //button.ImageAlign = System.Drawing.ContentAlignment.MiddleCenter;
                        //    button.HorizontalContentAlignment = HorizontalAlignment.Center;
                        //    button.VerticalContentAlignment = VerticalAlignment.Center;
                        //    button.Width = 44;
                        //}

                        if(!btnContent.Equals("<>"))
                        {
                           button.Content=btnContent;
                        }
                    });
                });
                // button.Content = _data.GetButtonText(tableName, lookupColumn, selectSQL);
                

            };
            info.Show();
           

           
            //String selectSQL = info.GetSelectedSQL();       //  C_Project_ID=100 or ""

            //// info = null;
            //// if (selectSQL == null || selectSQL.Length == 0 || key == null)
            //if (selectSQL == null || selectSQL.Length == 0)
            //{
            //    button.Content = "";
            //    //m_data.whereInfo.put(keyColumn, "");    //  no query
            //    _data.whereInfo.Remove(keyColumn);//remove select text from button by removeing key     //  no query
            //    button.Width = 44;
            //    return 0;
            //}

            ////  Save for query
            //log.Config(keyColumn + " - " + key);
            //if (button == vbtnSelctDoc)                            //  Record_ID
            //{
            //    _data.Record_ID = Utility.Util.GetValueOfInt(key);
            //}
            //else
            //{
            //    _data.whereInfo.Add(keyColumn, keyColumn + "=" + key);
            //}

            ////  Display Selection and resize
            //string btnContent = "";
            //System.Threading.ThreadPool.QueueUserWorkItem(delegate
            //{
            //    btnContent = _data.GetButtonText(tableName, lookupColumn, selectSQL);
            //    Dispatcher.BeginInvoke(delegate
            //    {
            //        button.Content = btnContent;
            //    });
            //});
            //// button.Content = _data.GetButtonText(tableName, lookupColumn, selectSQL);
            //if (!button.Content.Equals(""))
            //{
            //    //button.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //    button.HorizontalContentAlignment = HorizontalAlignment.Left;
            //    button.VerticalContentAlignment = VerticalAlignment.Center;
            //    //button.Width = button.Text.Length + 150;
            //    // button.AutoSize = true;
            //}
            //else
            //{
            //    //button.ImageAlign = System.Drawing.ContentAlignment.MiddleCenter;
            //    button.HorizontalContentAlignment = HorizontalAlignment.Center;
            //    button.VerticalContentAlignment = VerticalAlignment.Center;
            //    button.Width = 44;
            //}


           
           
           
          
            //pack();
           
            return 0;
        }

       

        /// <summary>
        /// RePost Record
        /// </summary>
        private void ActionRePost()
        {
             ShowMessage.AskMessage("PostImmediate?", true, "").Closed += (se, ev) =>
             {
                 if (true.Equals(((Message)se).DialogResult))
                 {
                     if (_data.documentQuery && _data.AD_Table_ID != 0 && _data.Record_ID != 0)
                     {

                         this.Cursor = Cursors.Wait;
                         bool force = (bool)vchkforcePost.IsChecked;
                         Ctx ctx = Envs.GetCtx();
                         Dictionary<string, string> dic = (Dictionary<String, string>)ctx.GetMap();
                         var client = AEnv.GetDSPWFClient();
                         client.PostImmediateCompleted += (s, e) =>
                         {
                             if (e.Result != null && e.Result.Length > 0)
                             {
                                 ShowMessage.Error(e.Result, true);

                             }
                             ActionQuery();
                             this.Cursor = Cursors.Arrow;
                             //  DataRowRefresh(true, null);
                         };
                         client.PostImmediateAsync(dic, _data.AD_Client_ID, _data.AD_Table_ID, _data.Record_ID, force, null);
                         // client.PostImmediateAsync(dic, _data.AD_Client_ID, _data.AD_Table_ID, _data.Record_ID, force, "");
                         client.CloseAsync();

                     }
                 }
              

             };
            
 //           if (_data.documentQuery
 //               && _data.AD_Table_ID != 0 && _data.Record_ID != 0
 //               && ShowMessage.Ask("PostImmediate?", true, ""))//.WindowNo, this, "PostImmediate?"))
  //          {
   //             this.Cursor = Cursors.Wait;
   //             bool force = (bool)vchkforcePost.IsChecked;

                //String error = AEnv.PostImmediate(Env.GetCtx(), _data.windowNo, _data.AD_Client_ID,
                //    _data.AD_Table_ID, _data.Record_ID, force);
                //this.Cursor = Cursors.Arrow;
                ////setCursor(Cursor.getDefaultCursor());
                //if (error != null)
                //{
                //    ShowMessage.Error(error, true);//"PostingError-N", 
                //}
                //ActionQuery();


                ////////////////////////////////////////////////////////////
               // String error = null;
                //ServerBean s;
                //TcpChannel tcp = new TcpChannel();

                //IChannel[] chans = ChannelServices.RegisteredChannels;
                //if (chans.Count() <= 0)
                //    ChannelServices.RegisterChannel(tcp, false);
                //try
                //{
  //              Ctx ctx = Envs.GetCtx();
 //               Dictionary<string, string> dic = (Dictionary<String, string>)ctx.GetMap();
               // s = (ServerBean)Activator.GetObject(typeof(ServerBean), "tcp://" + VConnection.Get().Apps_host + ":" + VConnection.Get().Apps_port + "/" + "ViennaFramework");
                //    string sttr = "";
                //    error = s.TryConnection(out sttr); //s.PostImmediate(Env.GetCtx(), _ctx.GetAD_Client_ID(), _curTab.GetAD_Table_ID(), _curTab.GetRecord_ID(), force, null);
                //  error = s.PostImmediate(dic, _data.AD_Client_ID, _data.AD_Table_ID, _data.Record_ID, force, null);
                //}
                //catch (Exception ex)
                //{
                //    ShowMessage.Error(ex.ToString(), true);
                //}

 //               var client = AEnv.GetDSPWFClient();
 //               client.PostImmediateCompleted += (s, e) =>
 //               {
 //                   if (e.Result != null && e.Result.Length > 0)
 //                   {
//                        ShowMessage.Error(e.Result, true);
//                        ActionQuery();
 //                   }
                  //  DataRowRefresh(true, null);
  //              };
 //              client.PostImmediateAsync(dic, _data.AD_Client_ID, _data.AD_Table_ID, _data.Record_ID, force, null);
               // client.PostImmediateAsync(dic, _data.AD_Client_ID, _data.AD_Table_ID, _data.Record_ID, force, "");
 //              client.CloseAsync();
                
                
                //if (error != null)
                //{
                //    ShowMessage.Error(error, true);
                //}
                
                ///////////////////////////////////////////////////////////
 //               this.Cursor = Cursors.Arrow;
 //           }
        }


        /// <summary>
        /// Fill a ComboBox using a list of NamePair objects
        /// </summary>
        /// <param name="cb">the ComboBox to fill</param>
        /// <param name="vo">the ListBoxVO containing the data</param>
        protected void FillComboBox(SLControls.Controls.VComboBox cb, ListBoxVO vo)
        {

            foreach (Object p in vo.GetOptions())//for( Object p : vo.GetOptions() )
            {
                cb.Items.Add(p);
                if (cb.Items.Count == 1)
                {
                    cb.SelectedIndex = 0;
                }
            }
            if (vo.GetDefaultKey() != null)
            {
                //string str = vo.GetDefaultKey();
                //for (int i = 0;i< cb.Items.Count; i++)
                //{
                //    ValueNamePair kp = (ValueNamePair)cb.Items[i];

                //    if (kp.GetValue() == str)
                //    {
                //        cb.SelectedIndex = i;
                //        return;
                //    }
                //}
                cb.SelectedItem = vo.GetDefaultKey();
            }
        }

        /// <summary>
        /// Tab Changed
        /// </summary>
        /// <param name="e"></param>
        public void StateChanged(object sender, EventArgs e)//(ChangeEvent e)
        {
            //	log.info( "AcctViewer.stateChanged");
            bool visible = _data.documentQuery && vTabmain.SelectedIndex == 1;
            if (visible == true)
            {
                vbtnRePost.Visibility = Visibility.Visible;
            }
            else
            {
                vbtnRePost.Visibility =  Visibility.Collapsed;
            }
            if (Envs.GetCtx().GetContext("#ShowAdvanced").Equals("Y"))
            {
               // vchkforcePost.Visible = visible;
                if (visible == true)
                {
                    vchkforcePost.Visibility = Visibility.Visible;
                }
                else
                {
                    vchkforcePost.Visibility = Visibility.Collapsed;
                }
            }
        }


        /// <summary>
        ///  Action Performed (Action Listener)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ActionPerformed(object sender, EventArgs e)//(ActionEvent e)
        {
            //	log.info(e.getActionCommand());
            Object source = sender;   //e.getSource();
            if (source == vcmbAccSchema)
            {
                ActionAcctSchema();
            }
            else if (source == vbtnRefresh)
            {
               
                ActionQuery();
              
            }
            else if (source == vbtnRefreshT2)
            {
               
                ActionQuery();
               
            }
            else if (source == vchkSelectDoc)
            {
                ActionDocument();
            }
            else if (source == vcmbSelectDoc)
            {
                ActionTable();
            }
            else if (source == vbtnRePost)
            {
              
                string invoiceID = "(SELECT ca.c_invoice_id FROM c_allocationline ca" +
                          " inner join c_invoice ci on ci.c_invoice_id= ca.c_invoice_id" +
                          " WHERE ci.issotrx='Y' and ca.c_allocationhdr_id=" + _data.Record_ID;
                string postValue = "SELECT (SELECT SUM(al.amount) FROM c_allocationline al INNER JOIN" +
                    " c_allocationhdr alh ON al.c_allocationhdr_id=alh.c_allocationhdr_id  WHERE " +
                    " alh.posted   ='Y' and c_invoice_id=" + invoiceID + ")) as aloc  ," +
                    "(SELECT SUM(cl.linenetamt)  FROM c_invoiceline cl WHERE " +
                    " c_invoice_id     =" + invoiceID + ")) as adj  from dual";

                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    IDataReader idr = DB.ExecuteReader(postValue);
                    try
                    {
                        if (idr.Read())
                        {
                            if (Util.GetValueOfDecimal(idr[0]) - Util.GetValueOfDecimal(idr[1]) == 0)
                            {
                                //reposting
                                string sql = "update c_allocationhdr alh set alh.posted ='N' where alh.c_allocationhdr_id in (select c_allocationhdr_id from c_allocationline where c_invoice_id=" + invoiceID + "))";
                                int val = DB.ExecuteQuery(sql);
                            }
                        }
                    }
                    catch { }

                    //Dispatcher.BeginInvoke(delegate
                    //{

                    //});
                });
               
                ActionRePost();
               
            }
            else if (source == vbtnPrint)
            {
                //PrintScreenPainter.printScreen(this);
            }
            else if (source == vbtnPrintT2)
            {
                //PrintScreenPainter.printScreen(this);
            }
            //  InfoButtons
            else if (source is SLControls.Controls.VImage)
            {
                ActionButton((SLControls.Controls.VImage)source);
            }
        }



        private void EventHadler()
        {
            vcmbAccSchema.SelectionChanged+=new SelectionChangedEventHandler(ActionPerformed);   
            vbtnRefresh.Click+=new RoutedEventHandler(ActionPerformed);
            vchkSelectDoc.Click +=new RoutedEventHandler(ActionPerformed);
            vcmbSelectDoc.SelectionChanged += new SelectionChangedEventHandler(ActionPerformed);
            vbtnRePost.Click += new RoutedEventHandler(ActionPerformed);
            vbtnPrint.Click += new RoutedEventHandler(ActionPerformed);

            //  InfoButtons
            vbtnAccount.Click += new RoutedEventHandler(ActionPerformed);
            vbtnBPartner.Click += new RoutedEventHandler(ActionPerformed);
            vbtnCampaning.Click += new RoutedEventHandler(ActionPerformed);
            vbtnPrintT2.Click += new RoutedEventHandler(ActionPerformed);
            vbtnProduct.Click += new RoutedEventHandler(ActionPerformed);
            vbtnProject.Click += new RoutedEventHandler(ActionPerformed);
            vbtnRefreshT2.Click += new RoutedEventHandler(ActionPerformed);
            btnSel5.Click += new RoutedEventHandler(ActionPerformed);
            btnSel6.Click += new RoutedEventHandler(ActionPerformed);
            btnSel7.Click += new RoutedEventHandler(ActionPerformed);
            btnSel8.Click += new RoutedEventHandler(ActionPerformed);
            vbtnSelctDoc.Click += new RoutedEventHandler(ActionPerformed);
            

            //Tab Event
            vTabmain.SelectionChanged+=new SelectionChangedEventHandler(this.ActionPerformed);

            
        }

       

      


    }
}
